﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;


namespace AppImporter
{
    public partial class Settings : Form
    {
        private LimCollectionBrowse LimCollectionBrowseDialog;
        public object SCCMWQLConnection;
        private XmlDocument guiConfig = new XmlDocument();
        
        public Settings()
        {
            InitializeComponent();

            //XDocument guiConfig = XDocument.Load(@"..\..\Settings.xml");
            
            guiConfig.Load(@".\Settings.xml");
           
            //MessageBox.Show(guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText.ToString());
            try
            {
                //#General
                tb_SCCMServer.Text = guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText;
                tb_SiteCode.Text = guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText;
                tb_SQLServer.Text = guiConfig.SelectSingleNode("/AppImporter/SQLServer").InnerText;
                tb_SQLDatabase.Text = guiConfig.SelectSingleNode("/AppImporter/SQLDatabase").InnerText;
                tb_AppFldBrowse.Text = guiConfig.SelectSingleNode("/AppImporter/AppFldRoot").InnerText;
                tb_prefix.Text = guiConfig.SelectSingleNode("/AppImporter/Prefix").InnerText;

                //Application
                cb_dpgroups.Text = guiConfig.SelectSingleNode("/AppImporter/DistributionGroupName").InnerText;
                switch (guiConfig.SelectSingleNode("/AppImporter/deploymentpurpose").InnerText)
                {
                    case "0":
                        cb_deploymentpurpose.Text = "Required";
                        break;
                    case "2":
                        cb_deploymentpurpose.Text = "Available";
                        break;        
                    default:
                        break;
                }
                switch (guiConfig.SelectSingleNode("/AppImporter/DeploymentReq").InnerText)
                {
                    case "True":
                        cb_DeploymentReq.Checked = true;
                        break;
                    case "False":
                        cb_DeploymentReq.Checked = false;
                        break;        
                    default:
                        break;
                }
                cb_PrimaryDeviceDeploymentReq.Text = guiConfig.SelectSingleNode("/AppImporter/PrimaryDeviceDeploymentReq").InnerText;
                

                //Collection
                tb__limitingcoll.Text = guiConfig.SelectSingleNode("/AppImporter/LimitingCollection").InnerText;
                tb__limitingcollname.Text = guiConfig.SelectSingleNode("/AppImporter/LimitingCollectionName").InnerText;
                switch (guiConfig.SelectSingleNode("/AppImporter/CollUpdateType").InnerText)
                {
                    case "2":
                        cb_CollUpdType.Text = "Periodic";
                        break;
                    case "4":
                        cb_CollUpdType.Text = "Incremental";
                        break;
                    case "6":
                        cb_CollUpdType.Text = "Periodic+Incremental";
                        break;
                    default:
                        break;
                }

                switch (guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText.ToString())
                {
                    case "5000":
                        cb_AppImpType.Text = "Device";
                        break;
                    case "5001":
                        cb_AppImpType.Text = "User";
                        break;
                    default:
                        break;
                }

                //ActiveDirectory
                tb_ADDomain.Text = guiConfig.SelectSingleNode("/AppImporter/ADDomain").InnerText;
                tb_groupOU.Text = guiConfig.SelectSingleNode("/AppImporter/GroupOU").InnerText;

            }
            catch
            {
                MessageBox.Show("Settings.xml is corrupt, cannot load all properties correctly!");
            }
            finally { }
        }

        public event ValueUpdatedEventHandler ValueUpdated;

        private void CollectionBrowse_Load(object sender, EventArgs e)
        {

        }

        private void vScrollBar1_Scroll(object sender, ScrollEventArgs e)
        {

        }

        private void bt_save_Click(object sender, EventArgs e)
        {
            #region Set Settings
            //General
            guiConfig.SelectSingleNode("/AppImporter/SCCMServer").InnerText = tb_SCCMServer.Text;
            guiConfig.SelectSingleNode("/AppImporter/SCCMSiteCode").InnerText = tb_SiteCode.Text;
            guiConfig.SelectSingleNode("/AppImporter/SQLServer").InnerText = tb_SQLServer.Text;
            guiConfig.SelectSingleNode("/AppImporter/SQLDatabase").InnerText = tb_SQLDatabase.Text;
            guiConfig.SelectSingleNode("/AppImporter/Prefix").InnerText = tb_prefix.Text;
            guiConfig.SelectSingleNode("/AppImporter/AppFldRoot").InnerText = tb_AppFldBrowse.Text;
            
            //Application
            if (cb_dpgroups.Text != "")
            {
                try
                {
                    guiConfig.SelectSingleNode("/AppImporter/DistributionGroupName").InnerText = cb_dpgroups.Text;

                    this.SCCMWQLConnection = this.Connect(tb_SCCMServer.Text);
                    WqlConnectionManager connection = (WqlConnectionManager)SCCMWQLConnection;
                    string query = "SELECT * FROM SMS_DistributionPointGroup WHERE Name='" + cb_dpgroups.Text +"'";
                    IResultObject DPGroupList = connection.QueryProcessor.ExecuteQuery(query);
                    

                    foreach (IResultObject DPGroup in DPGroupList)
                    {
                        guiConfig.SelectSingleNode("/AppImporter/DistributionGroupID").InnerText = DPGroup["GroupID"].StringValue;
                        //MessageBox.Show(DPGroup["GroupID"].StringValue);
                    }
                }
                catch
                {
                }
                finally
                {
                }
            }

            switch (cb_deploymentpurpose.Text)
            {
                case "Required":
                    guiConfig.SelectSingleNode("/AppImporter/deploymentpurpose").InnerText = "0";
                    break;
                case "Available":
                    guiConfig.SelectSingleNode("/AppImporter/deploymentpurpose").InnerText = "2";
                    break;
                default:
                    break;
            }

            switch (cb_DeploymentReq.Checked.ToString())
            {
                case "True":
                    guiConfig.SelectSingleNode("/AppImporter/DeploymentReq").InnerText = "True";
                    break;
                case "False":
                    guiConfig.SelectSingleNode("/AppImporter/DeploymentReq").InnerText = "False";
                    break;
                default:
                    break;
            }

            switch (cb_PrimaryDeviceDeploymentReq.Text)
            {
                case "True":
                    guiConfig.SelectSingleNode("/AppImporter/PrimaryDeviceDeploymentReq").InnerText = "True";
                    break;
                case "False":
                    guiConfig.SelectSingleNode("/AppImporter/PrimaryDeviceDeploymentReq").InnerText = "False";
                    break;
                default:
                    break;
            }

            //Collection
            guiConfig.SelectSingleNode("/AppImporter/LimitingCollection").InnerText = tb__limitingcoll.Text;
            guiConfig.SelectSingleNode("/AppImporter/LimitingCollectionName").InnerText = tb__limitingcollname.Text;
            switch (cb_CollUpdType.SelectedItem.ToString())
            {
                case "Periodic":
                    guiConfig.SelectSingleNode("/AppImporter/CollUpdateType").InnerText = "2";
                    break;
                case "Incremental":
                    guiConfig.SelectSingleNode("/AppImporter/CollUpdateType").InnerText = "4";
                    break; //goto case 1;
                case "Periodic+Incremental":
                    guiConfig.SelectSingleNode("/AppImporter/CollUpdateType").InnerText = "6";
                    break; //goto case 1;
                default:
                    Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
                    break;
            }

            switch (cb_AppImpType.SelectedItem.ToString())
            {
                case "Device":
                    guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText = "5000";
                    break;
                case "User":
                    guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText = "5001";
                    break; //goto case 1;
                default:
                    Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
                    break;
            }

            //ActiveDirectory
            guiConfig.SelectSingleNode("/AppImporter/ADDomain").InnerText = tb_ADDomain.Text;
            guiConfig.SelectSingleNode("/AppImporter/GroupOU").InnerText = tb_groupOU.Text;


            #endregion Set Settings

            try
            {
                guiConfig.Save(@".\Settings.xml");
                string newValue = "true";
                ValueUpdatedEventArgs valueArgs = new ValueUpdatedEventArgs(newValue);
                ValueUpdated(this, valueArgs);
                Dispose();
            }
            catch
            {
                MessageBox.Show("Unable to save settings, make sure you are either running the program as an administrator \n" +
                    "or that make sure 'Settings.xml' is writable in the install dir.");
            }

        }

        private void openFolderDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void bt_AppFldBrowse_Click(object sender, EventArgs e)
        {
            //openFileDialog1.InitialDirectory = strmsipath;
            DialogResult result = openFolderDialog1.ShowDialog(); // Show the dialog and get result.
            if (result == DialogResult.OK) // Test result.
            {

                //    string directoryPath = Path.GetDirectoryName(openFileDialog1.FileName);
                //strmstfilename = Path.GetFileName(openFileDialog1.FileName);
                //tb_mstpath.Text = strmstfilename;
                tb_AppFldBrowse.Text = openFolderDialog1.SelectedPath;
                guiConfig.SelectSingleNode("/AppImporter/AppFldRoot").InnerText = tb_AppFldBrowse.Text;
            }
        }

        private void cb_dpgroups_DropDown(object sender, EventArgs e)
        {
            if (cb_dpgroups.Items.Count == 0 && cb_dpgroups.Text == guiConfig.SelectSingleNode("/AppImporter/DistributionGroupName").InnerText)
            {
                try
                {

                    this.SCCMWQLConnection = this.Connect(tb_SCCMServer.Text);
                    WqlConnectionManager connection = (WqlConnectionManager)SCCMWQLConnection;
                    string query = "SELECT * FROM SMS_DistributionPointGroup";
                    IResultObject DPGroupList = connection.QueryProcessor.ExecuteQuery(query);

                    foreach (IResultObject DPGroup in DPGroupList)
                    {
                        cb_dpgroups.Items.Add(DPGroup["Name"].StringValue);
                    }
                }
                catch
                {
                }
                finally
                {
                }
            }
        }

        private void bt_limcollbrowse_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            try
            {
                this.LimCollectionBrowseDialog = new LimCollectionBrowse();
                this.LimCollectionBrowseDialog.ValueUpdated += new ValueUpdatedEventHandler(LimCollectionBrowseDialog_ValueUpdated);
                //ClientInstallDialog.openFileDialog1.InitialDirectory = @"\\" + oSMSClient.ManagementPoint;
                if (LimCollectionBrowseDialog.ShowDialog(this) == DialogResult.OK)
                {

                }
            }
            catch (SystemException ex)
            {
                //Ballontip("Error", ex.Message, ToolTipIcon.Error, 6000);
                //desktopAlert1.ShowAlert(ex.ToString());
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void LimCollectionBrowseDialog_ValueUpdated(object sender, ValueUpdatedEventArgs e)
        {
            // Update the text box on this form (the parent) with the new value
            string s = e.NewValue;
            //MessageBox.Show(s);
            string[] collfldarr = s.Split(';');

            this.tb__limitingcoll.Text = collfldarr[0];
            this.tb__limitingcollname.Text = collfldarr[1];

            //this.tb_collid.Text = e.NewValue;
        }

        private void cb_AppImpType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (cb_AppImpType.SelectedItem.ToString())
            {
                case "Device":
                    guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText = "5000";
                    break;
                case "User":
                    guiConfig.SelectSingleNode("/AppImporter/AppImpType").InnerText = "5001";
                    break; //goto case 1;
                default:
                    Console.WriteLine("Invalid selection. Please select 1, 2, or 3.");
                    break;
            }

            guiConfig.Save(@".\Settings.xml");

            tb__limitingcoll.Text = "";
            tb__limitingcollname.Text = "";
        }

       public WqlConnectionManager Connect(string serverName) //, string userName, string userPassword)

        {
            try
            {
                SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
                WqlConnectionManager connection = new WqlConnectionManager(namedValues);
                if (System.Net.Dns.GetHostName().ToUpper() == serverName.ToUpper())
                {
                    connection.Connect(serverName);
                }
                else
                {
                    connection.Connect(serverName);//, userName, userPassword);

                }
                return connection;
            }
            catch (SmsException ex)
            {
                Console.WriteLine("Failed to Connect. Error: " + ex.Message);
                return null;
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Failed to authenticate. Error:" + ex.Message);
                return null;
            }
        }
    }
}
